﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace Update
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process p in ps)
            {
                if (p.ProcessName.ToLower() == "enamonitor")
                {
                    //MessageBox.Show(p.ProcessName);
                    p.Kill();
                    break;
                }
            }
            MessageBox.Show("检测到软件有新版本，马上更新。");
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + @"\Update.xml");
            XmlElement root = doc.DocumentElement;
            XmlNode updateNode = root.SelectSingleNode("filelist");
            string path = updateNode.Attributes["sourcepath"].Value;
            int count = int.Parse(updateNode.Attributes["count"].Value);
            for (int i = 0; i < count; i++)
            {
                XmlNode itemNode = updateNode.ChildNodes[i];
                string fileName = itemNode.Attributes["name"].Value;
                FileInfo fi = new FileInfo(fileName);
                fi.Delete();
                //File.Delete(Application.StartupPath + @"\" + fileName);
                this.label1.Text = "正在更新： " + fileName + " (" + itemNode.Attributes["size"].Value + ") ...";
                FileStream fs = File.Open(fileName, FileMode.Create, FileAccess.Write);
                fs.Write(System.Convert.FromBase64String(itemNode.SelectSingleNode("value").InnerText), 0, int.Parse(itemNode.Attributes["size"].Value));
                fs.Close();
            }
            label1.Text = "更新完成";
            File.Delete(Application.StartupPath + @"\update.xml");
            label1.Text = "正在重新启动应用程序...";
            System.Diagnostics.Process.Start("ENAMonitor.exe");
            Close();
            Application.Exit();
        }
    }
}
